import { computed, ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { $t, locale, locales } from '@/i18n'
import { NAVS } from '@/constant'

export const useHeadStore = defineStore('app-head', () => {
  const title = ref(
    import.meta.env.DEV 
      ? $t('meta.home.title', { pipe: '|' })
      : document.querySelector('head title').textContent, // prettier-ignore
  )
  const description = ref(
    import.meta.env.DEV
      ? $t('meta.home.description')
      : document.querySelector('meta[name="description"]').getAttribute('content'),
  )
  const keywords = ref(
    import.meta.env.DEV
      ? $t('meta.home.keywords')
      : document.querySelector('meta[name="keywords"]').getAttribute('content'),
  )

  const ogTitle = computed(() => title.value)
  const ogDescription = computed(() => description.value)
  const ogUrl = ref(import.meta.env.VITE_APP_URL ?? 'https://www.fantasi.one')
  const ogType = 'website'
  const ogImage = ref(import.meta.env.VITE_APP_URL + (import.meta.env.VITE_APP_OG_IMAGE ?? '/seo/og-image.jpg'))

  const twitterTitle = computed(() => title.value)
  const twitterDescription = computed(() => description.value)
  const twitterImage = ref(
    import.meta.env.VITE_APP_URL + (import.meta.env.VITE_APP_TWITTER_IMAGE ?? '/seo/twitter-image.jpg'),
  )

  const alternates = ref([
    ...locales.map((locale) => ({
      rel: 'alternate',
      hreflang: locale.label.replace('_', '-'),
      href: `${import.meta.env.VITE_APP_URL}/${locale.label}/home`,
    })),
    {
      rel: 'alternate',
      hreflang: 'x-default',
      href: `${import.meta.env.VITE_APP_URL}/en/home`,
    },
  ])

  const currentPage = ref(NAVS.HOME)
  const dataTemp = ref({})

  // 複合式搜尋結果頁面，預設關閉
  const itemscope = ref(false)
  const itemtype = ref(null)

  function toHomeHead({ isRefresh = false } = {}) {
    if (!isRefresh) {
      currentPage.value = NAVS.HOME
      dataTemp.value = {}
    }

    title.value = $t('meta.home.title', { pipe: '|' })
    description.value = $t('meta.home.description')
    keywords.value = $t('meta.home.keywords')
    ogUrl.value = import.meta.env.VITE_APP_URL ?? 'https://www.fantasi.one'
    ogImage.value = ogUrl.value + (import.meta.env.VITE_APP_OG_IMAGE ?? '/seo/og-image.jpg')
    twitterImage.value = ogUrl.value + (import.meta.env.VITE_APP_TWITTER_IMAGE ?? '/seo/twitter-image.jpg')
  }

  function toSearchHead({ path = '', keyword = '', isRefresh = false } = {}) {
    if (!isRefresh) {
      currentPage.value = NAVS.SEARCH
      dataTemp.value = { path, keyword }
    }

    const _path = isRefresh ? dataTemp.value.path : path
    const _keyword = isRefresh ? dataTemp.value.keyword : keyword

    ogUrl.value = import.meta.env.VITE_APP_URL + _path
    if (_keyword) {
      title.value = $t('meta.searchResult.title', { keyword: _keyword, pipe: '|' })
      description.value = $t('meta.searchResult.description', { keyword: _keyword })
      keywords.value = $t('meta.searchResult.keywords', { keyword: _keyword })
    } else {
      title.value = $t('meta.search.title', { pipe: '|' })
      description.value = $t('meta.search.description')
      keywords.value = $t('meta.search.keywords')
    }
  }

  function toMineHead({ path = '', isRefresh = false } = {}) {
    if (!isRefresh) {
      currentPage.value = NAVS.MINE
      dataTemp.value = { path }
    }

    const _path = isRefresh ? dataTemp.value.path : path

    title.value = $t('meta.mine.title', { pipe: '|' })
    description.value = $t('meta.mine.description')
    keywords.value = $t('meta.mine.keywords')
    ogUrl.value = import.meta.env.VITE_APP_URL + _path
  }

  function toCreatorHead({ pageUrl = '', creator = {}, isRefresh = false } = {}) {
    if (!isRefresh) {
      currentPage.value = NAVS.CREATOR
      dataTemp.value = { pageUrl, creator }
    }

    const _pageUrl = isRefresh ? dataTemp.value.pageUrl : pageUrl
    const _creator = isRefresh ? dataTemp.value.creator : creator

    title.value = $t('meta.creator.title', { name: _creator.nickname, pipe: '|' })
    description.value = $t('meta.creator.description', { name: _creator.nickname, bio: _creator.bio })
    ogUrl.value = _pageUrl
    keywords.value = $t('meta.creator.keywords', { name: _creator.nickname })
  }

  function toPopularCreatorHead() {
    title.value = $t('meta.popularCreator.title')
    description.value = $t('meta.popularCreator.description')
    keywords.value = $t('meta.popularCreator.keywords')
  }

  function toTagHead({ title: _title, description: _description, keywords: _keywords } = {}) {
    title.value = _title
    description.value = _description
    keywords.value = _keywords
  }

  function toBlogArticleHead(detailData) {
    title.value = detailData.title
    description.value = detailData.meta_description
    keywords.value = detailData.meta_keywords
    itemscope.value = true
    itemtype.value = `${location.origin}/blog/${detailData.url_address}`
  }

  function toSignUpHead({ isRefresh = false } = {}) {
    if (!isRefresh) currentPage.value = NAVS['SIGN-UP']
    title.value = $t('meta.signUp.title')
    description.value = $t('meta.signUp.description')
    keywords.value = $t('meta.signUp.keywords')
  }

  function toMediaHead(feed) {
    if (!feed) {
      return
    }

    title.value = `${feed.author?.nickname} ${feed.content} - Fantasi`
    description.value = feed.content
    keywords.value = feed.tags
  }

  watch(locale, () => {
    switch (currentPage.value) {
      case NAVS.HOME:
        toHomeHead()
        break
      case NAVS.SEARCH:
        toSearchHead({ isRefresh: true })
        break
      case NAVS.MINE:
        toMineHead({ isRefresh: true })
        break
      case NAVS.CREATOR:
        toCreatorHead({ isRefresh: true })
        break
      case NAVS['SIGN-UP']:
        toSignUpHead({ isRefresh: true })
        break
    }
  })

  return {
    title,
    description,
    keywords,
    ogTitle,
    ogDescription,
    ogUrl,
    ogType,
    ogImage,
    twitterTitle,
    twitterDescription,
    twitterImage,
    alternates,
    itemscope,
    itemtype,
    toHomeHead,
    toSearchHead,
    toMineHead,
    toCreatorHead,
    toPopularCreatorHead,
    toTagHead,
    toBlogArticleHead,
    toSignUpHead,
    toMediaHead,
  }
})
